package com.bdqn.t350.vue.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bdqn.t350.vue.bean.Dto;
import com.bdqn.t350.vue.bean.LoginUser;
import com.bdqn.t350.vue.bean.User;
import com.bdqn.t350.vue.mapper.UserMapper;
import com.bdqn.t350.vue.utils.JwtTokenUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.bdqn.t350.vue.service.UserService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImp implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    AuthenticationManager authenticationManager;

    @Resource
    RedisTemplate redisTemplate;

    /**
     * 登录认证的业务流程
     *
     * @param user
     * @return
     * @throws Exception
     */
    public Dto login(User user) {
        //Authentication进行验证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsrName(), user.getUsrPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException(("登录异常!!!"));
        }
        //LoginUser 返回前端的用户对象
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String useId = loginUser.getUser().getUsrId().toString();
        Dto dto = new Dto();
        try {
            //认证成功生成jwt
            String jwt = JwtTokenUtil.createSign(useId);
            //将jwt保存到redis中
            redisTemplate.opsForValue().set("loginUserId:" + useId, loginUser);
            dto.setMsg("登录成功");
            dto.setErrorCode("200");
            dto.setSuccess("true");
            Map<String, String> map = new HashMap<>();
            map.put("token", jwt);
            dto.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dto;
    }

    @Override
    public Dto logout() {
        //通过SecurityContextHolder获取用户id
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long usrId = loginUser.getUser().getUsrId();
        //删除redis中的usrId
        //redisUtil.del("loginUserId:" + usrId);
        Boolean bool = redisTemplate.delete("loginUserId:" + usrId);
        System.out.println(bool);
        Dto dto = new Dto();
        dto.setSuccess("true");
        dto.setMsg("退出成功");
        return dto;
    }


    @Override
    public User selectByName(String usrName) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("usr_name", usrName);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @Override
    public IPage<User> selectPage(IPage<User> page, QueryWrapper queryWrapper) {
        return userMapper.selectPage(page, queryWrapper);
    }

    @Override
    public int deleteById(int id) {
        return userMapper.deleteById(id);
    }

    @Override
    public int updateById(User user) {
        return userMapper.updateById(user);
    }

}
